package com.ccys.netty.handler;

import com.ccys.common.enums.CodeEnum;
import com.ccys.common.util.JedisUtil;
import com.ccys.common.util.Kit;
import com.ccys.common.util.StringUtil;
import com.ccys.netty.config.NettyConfig;
import com.ccys.netty.content.BaseConstant;
import io.grpc.netty.shaded.io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.text.DateFormat;
import java.util.Date;

   /**
    * @description 心跳处理
    * @date     2024/3/4
    * @author   cloud fly
    */

@Slf4j
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

    private int lossConnectCount = 3;
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("===心跳检测方法执行时间："+ Kit.formatDateTime(new Date(),"yyyy-MM-dd HH:mm:ss")+"===");
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;
            boolean first = event.isFirst();
            String channelBookingId = WebSocketFrameHandler.getChannelBookingId(ctx);
            if(StringUtil.isNotEmpty(channelBookingId)) {
                //服务端对应着读写事件，当为读写都空闲时触发
                if (event.state()== IdleState.ALL_IDLE){
                    ctx.writeAndFlush(new TextWebSocketFrame("Connection inactive timeout 关闭不活动的链接"));
                    //关闭通道
                    log.info("关闭不活动的链接,链接id:{}",ctx.channel().id().asLongText());
                    ctx.channel().close();
                    //删除缓存的通道关系
                    NettyConfig.getUserChannelMap().remove(channelBookingId);
                    //删除缓存的通道状态
                    JedisUtil.del("bookingId:" + channelBookingId,CodeEnum.REDIS_HEARTBEAT.codeOf());
                } else if (event.state() == IdleState.WRITER_IDLE) {
                    //更新bookingId 通道时间
                    String setex = JedisUtil.setex("bookingId:" + channelBookingId, BaseConstant.HEARTBEAT + 10, ctx.channel().id().asLongText(), CodeEnum.REDIS_HEARTBEAT.codeOf());
                    log.info("bookingId通道缓存结果--->" + setex);
                    log.info("在线bookingId:" + Kit.getOnLineBookingIds());
                }else{
                    //ctx.writeAndFlush(new TextWebSocketFrame("pong"));
                    //更新bookingId 通道时间
                    String setex = JedisUtil.setex("bookingId:" + channelBookingId, BaseConstant.HEARTBEAT + 10, ctx.channel().id().asLongText(), CodeEnum.REDIS_HEARTBEAT.codeOf());
                    log.info("bookingId通道缓存结果--->" + setex);
                    log.info("在线bookingId:" + Kit.getOnLineBookingIds());
                }
            }

        }else {
            super.userEventTriggered(ctx,evt);
        }
    }
}
